package com.InfinityRun;

import android.R.color;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Bitmap.Config;
import android.sax.StartElementListener;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

public class MainGame extends Activity 
{
	private static int FRAME_WIDTH, FRAME_HEIGHT;
	private int SCREEN_WIDTH, SCREEN_HEIGHT;
	static boolean pause;
	WakeLock wakelock;
	RenderView view = null;
	SceneManager sceneManager;
	static Context ctx;

	class RenderView extends SurfaceView implements Runnable
	{
		private long time = 1;
	    Canvas canvas;
		Assets assets;
		SurfaceHolder holder;
		Bitmap frameBuffer;
		Thread renderThread = null;
		
	    volatile boolean running = false;
	    
		public RenderView(Context context, boolean isEscape, int bufferW, int bufferH) 
		{
			super(context);
			frameBuffer = Bitmap.createBitmap(bufferW,
					bufferH, Config.RGB_565);
			
	        holder = getHolder();

	        canvas = new Canvas(frameBuffer);
	        
			pause = false;
			assets = new Assets(context);
			
			if(isEscape)
			{
				sceneManager = SceneManager.getInstance(true, SCREEN_WIDTH, SCREEN_HEIGHT);	
			}
			
			else
			{
				sceneManager = SceneManager.getInstance(false, SCREEN_WIDTH, SCREEN_HEIGHT);			
			}
		}
		
		@Override
		public void run() 
		{
	        long startTime = System.nanoTime();
	        Rect dstRect = new Rect();
	        
			while(running)
			{
				if(!holder.getSurface().isValid())
	                continue;
				float deltaTime = (System.nanoTime() - startTime) / 1000000000.0f;
				startTime = System.nanoTime();
				
				update(deltaTime);
				draw();
	            postInvalidate();

				Canvas canvas = holder.lockCanvas();
				canvas.getClipBounds(dstRect);
	            canvas.drawBitmap(frameBuffer, null, dstRect, null);      
	            holder.unlockCanvasAndPost(canvas);
			}
		}
		
		public void update(float deltaTime)
		{
			sceneManager.actualScene.Update(deltaTime);
		}
		
		public boolean onTouchEvent(MotionEvent ev)
		{
			sceneManager.actualScene.GetInput(ev);
			return true;
		}
		
		public void draw()
		{
			sceneManager.actualScene.Draw(canvas);
		}
		
		public void Resume()
		{
			running = true;
	        renderThread = new Thread(this);
	        renderThread.start();
		}
		
		public void Pause()
		{
			running = false;                        
	        while(true) 
	        {
	            try 
	            {
	                renderThread.join();
	                break;
	            } 
	            catch (InterruptedException e)
	            {
	            }
	        }
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		ctx = this;
		
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
		String msg = "";
		Intent i = getIntent();

		if(i != null)
		{
		      Bundle params = i.getExtras();
		      if(params != null)
		      {
		    	  msg = params.getString("msg");
		    	  Log.d("testes", msg);
		      }
		}

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        

        boolean isLandscape = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;

        SCREEN_WIDTH = getWindowManager().getDefaultDisplay().getWidth();
        SCREEN_HEIGHT = getWindowManager().getDefaultDisplay().getHeight();
		FRAME_WIDTH = isLandscape ? 800 : 480;
		FRAME_HEIGHT = isLandscape ? 480 : 800;
	      
        if(msg.equalsIgnoreCase("ok"))
        {
        	view = new RenderView(this,true,FRAME_WIDTH,FRAME_HEIGHT);
        }
        
        else
        {
        	view = new RenderView(this,false,FRAME_WIDTH,FRAME_HEIGHT);
        }
        
        setContentView(view);
        
        PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wakelock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "GAME");
	}
	
	public static void GoToEscape(boolean win)
	{
		Intent i = new Intent("Escape");
		
		Bundle params = new Bundle();
		params.putBoolean("win", win);

		i.putExtras(params);	
		ctx.startActivity(i);
	}
	public static int getWidth()
	{
		return FRAME_WIDTH;
	}
	
	public static int getHeight()
	{
		return FRAME_HEIGHT;
	}
	
	protected void onPause()
	{
		super.onPause();
        wakelock.release();
		view.Pause();
		sceneManager.actualScene.OnPause();
	}
	
	protected void onResume()
	{
		super.onResume();
		wakelock.acquire();
		sceneManager.actualScene.OnResume();
		view.Resume();
	}
	
	protected void onDestroy()
	{
		super.onDestroy();
		sceneManager.Destroy();
	}
}
